﻿using UnityEngine;
using System.Collections;

public class Mover : MonoBehaviour {

    // some constants for the size and the location of the pause menu, the score max and the limit position of the players

    public const int WIDTH_MENU_PAUSE = 300;
    public const int HEIGHT_MENU_PAUSE = 400;
    public const int WIDTH_BUTTON = 200;
    public const int HEIGHT_BUTTON = 50;
    public const int PADDING_BUTTON = 40;
    public const int MAX_SCORE = 11;
    public const int PLAYER_LIMIT = -15;
    public const int OPPONENT_LIMIT = 15;

	public GameObject touchBall;
	public Transform touchBallSpawn;
	public GameObject shadow;

	private Vector3 direction;
    private float speed;
    private bool paused;
    private bool pointStarted = false;

    /// <summary>
    /// Starts this instance.
    /// </summary>
	void Start(){
        StartCoroutine("InitializeGame");
	}

    /// <summary>
    /// Initializes the game and wait for space button in order to continu.
    /// </summary>
    /// <returns></returns>
    IEnumerator InitializeGame()
    {
        transform.position = new Vector3(0.0f, 7.5f, -2.5f);
        this.direction = Vector3.zero;

        while (Application.isPlaying)
        {
            if (Input.GetKeyDown(KeyCode.Space) && pointStarted == false)
            {
                // initialize the speed and the direction of the ball.
                this.speed = -0.2f;
                this.direction = new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), 1.0f).normalized;
                pointStarted = true;
                yield return new WaitForSeconds(0.001f);
            }
            yield return new WaitForSeconds(0.001f);
        }
    }

    /// <summary>
    /// Updates this instance, called once per frame.
    /// </summary>
	void Update ()
	{
        // pause or unpause when the player press escape.
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            paused = !paused;
        }

        if (!paused)
        {
            Screen.showCursor = false;

            if (!GameObject.Find("Background").audio.isPlaying)
            {
                GameObject.Find("Background").audio.Play();
            }
            
            Time.timeScale = 1;     // restart the time and set it to normal
            Scores score = GameObject.Find("Camera").GetComponent<Scores>();

            if (this.transform.position.z < PLAYER_LIMIT)
            {
                //increase opponent score
                score.IncreaseScore(2);
                pointStarted = false;

                if (score.OpponentScore == MAX_SCORE)
                {
                    PlayerPrefs.SetInt("winner", 2);
                    Application.LoadLevel("endGame");
                }
                else
                {
                    StartCoroutine("InitializeGame");
                }
                
            }
            else if (this.transform.position.z > OPPONENT_LIMIT)
            {
                //increase player score
                score.IncreaseScore(1);
                pointStarted = false;

                if (score.PlayerScore == MAX_SCORE)
                {
                    PlayerPrefs.SetInt("winner", 1);
                    Application.LoadLevel("endGame");
                }
                else
                {
                    StartCoroutine("InitializeGame");
                }
                
            }

            this.transform.position += direction * speed;
            this.shadow.transform.position = new Vector3(this.transform.position.x, 0.2f, this.transform.position.z);
        }
        else
        {
            Time.timeScale = 0;
            GameObject.Find("Background").audio.Pause();
        }
	}

    /// <summary>
    /// Called when [collision enter].
    /// </summary>
    /// <param name="collision">The collision.</param>
	void OnCollisionEnter(Collision collision)
	{
		Vector3 normal = collision.contacts[0].normal;
		direction = Vector3.Reflect(direction, normal);
		if (collision.gameObject.name == "Player" || collision.gameObject.name == "Opponent") {
			Instantiate(touchBall, touchBallSpawn.position, touchBallSpawn.rotation);
			speed -= 0.02f;
		}
	}

    /// <summary>
    /// redraw GUI element at each frame
    /// </summary>
    void OnGUI()
    {
        if (paused)
        {
            Screen.showCursor = true;

            // create a box with 3 buttons that make a pause menu.

            GUI.Box(new Rect(Screen.width / 2 - WIDTH_MENU_PAUSE / 2, Screen.height / 2 - HEIGHT_MENU_PAUSE/2, WIDTH_MENU_PAUSE, HEIGHT_MENU_PAUSE), "PAUSE");

            if (GUI.Button(new Rect(Screen.width / 2 - WIDTH_BUTTON / 2, Screen.height / 2 - HEIGHT_BUTTON / 2 - PADDING_BUTTON * 3, WIDTH_BUTTON, HEIGHT_BUTTON), "RESUME"))
            {
                paused = false;
            }

            if (GUI.Button(new Rect(Screen.width / 2 - WIDTH_BUTTON / 2, Screen.height / 2 - HEIGHT_BUTTON / 2, WIDTH_BUTTON, HEIGHT_BUTTON), "MENU"))
            {
                Application.LoadLevel("menu");
            }

            if (GUI.Button(new Rect(Screen.width / 2 - WIDTH_BUTTON / 2, Screen.height / 2 - HEIGHT_BUTTON / 2 + PADDING_BUTTON * 3, WIDTH_BUTTON, HEIGHT_BUTTON), "QUIT"))
            {
                Application.Quit();
            }
        }

    }
}
